package com.jaychen.eureka.result;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

/**
 * ResponseBody返回处理统一json格式
 * 实现ResponseBodyAdvice接口，进行扩展，自定义处理
 *
 * @author longyuan
 */
@ControllerAdvice
public class GlobalResponseBodyHandler implements ResponseBodyAdvice<Object> {

    /**
     * 判断是否要执行beforeBodyWrite方法
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        RestController restController = methodParameter.getMethod().getDeclaringClass().getDeclaredAnnotation(RestController.class);
        return Objects.nonNull(restController);
    }

    /**
     * 处理返回结果
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (null != body) {
            return body.getClass() != Result.class && body.getClass() != String.class ? Result.success(body) : body;
        } else {
            Class<?> returnClass = methodParameter.getParameterType();
            if (Collection.class.isAssignableFrom(returnClass) || returnClass.isArray()) {
                body = Collections.emptyList();
            }
            return Result.success(body);
        }
    }
}
